/**
* ChatsonicView.vue - 讯飞星火AI聊天页面
*/

<script setup>
import { defineOptions, ref, onMounted, onActivated, onDeactivated, nextTick } from 'vue'
import { ElMessage } from 'element-plus';
import { ChatDotRound, ChatLineRound, Service, User, Position, Loading } from '@element-plus/icons-vue';
import chatsonicPost from '../services/chatsonicPost.js'; // 修改导入语句以匹配新的导出方式

defineOptions({
  name: 'Chatsonic'
})

// 组件状态
const messages = ref([]); // 聊天消息历史
const inputMessage = ref(''); // 用户输入
const loading = ref(false); // 加载状态
const messageContainerRef = ref(null); // 添加消息容器引用

// AI参数设置
const aiSettings = ref({
  model: 'generalv3.5',
  temperature: 1.0,
  top_p: 1,
  top_k: 4,
  presence_penalty: 0,
  frequency_penalty: 0,
  max_tokens: 4096,
  stream: false
});

// 模型选项
const modelOptions = [
  { label: 'Lite', value: 'lite' },
  { label: 'Pro', value: 'generalv3' },
  { label: 'Pro-128K', value: 'pro-128k' },
  { label: 'Max', value: 'generalv3.5' },
  { label: 'Max-32K', value: 'max-32k' },
  { label: '4.0 Ultra', value: '4.0Ultra' }
];

// 添加延迟函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// 组件被激活时触发
onActivated(() => {
  nextTick(() => {
    if (messageContainerRef.value) {
      messageContainerRef.value.scrollTop = messageContainerRef.value.scrollHeight;
    }
  });
});

// 组件被停用时触发
onDeactivated(() => {
  // console.log('Component deactivated');
  // 可以在这里处理一些停用时的逻辑
});

/**
 * 发送消息到后端API
 * @param {string} content - 用户输入的消息内容
 */
const handleSendMessage = async (content) => {
  if (!content.trim() || loading.value) return;

  try {
    loading.value = true;
    await delay(100);

    // 添加用户消息到消息列表
    messages.value.push({ role: 'user', content });
    // console.log('content:', messages.value);

    // 发送消息到讯飞星火API
    const response = await chatsonicPost.sendSparkRequest({
      messages: messages.value,
      model: 'generalv3.5',
      temperature: 0.7,
      top_p: 0.8,
      max_tokens: 2048
    });

    // 添加 AI 回复
    if (response && response.choices && response.choices[0]?.message) {
      messages.value.push(response.choices[0].message);
    } else {
      throw new Error('无效的API响应');
    }

    // 清空输入框
    inputMessage.value = '';

    // 滚动到底部
    await nextTick();
    scrollToBottom();
  } catch (error) {
    console.error('Error:', error);
    
    // 根据错误类型显示不同的错误提示
    let errorMessage = error.message;
    
    // 处理特定的错误码
    if (error.code) {
      switch(error.code) {
        case 10007:
          errorMessage = '请等待上一个问题处理完成后再发送新的请求';
          break;
        case 10013:
          errorMessage = '输入内容审核不通过，请调整输入内容';
          break;
        case 10014:
          errorMessage = '输出内容涉及敏感信息，无法显示';
          break;
        case 10019:
          errorMessage = '输入内容可能涉及违规信息，请调整';
          break;
        case 10907:
          errorMessage = '对话历史与问题字数超过上限，请精简输入';
          break;
        case 11200:
          errorMessage = '该账号没有相关功能的授权或业务量超过限制';
          break;
        case 11201:
          errorMessage = '已超过当日最大访问量限制';
          break;
        case 11202:
          errorMessage = '秒级访问超过限制';
          break;
        case 11203:
          errorMessage = '并发访问超过限制';
          break;
      }
    }
    
    // 使用Element Plus的消息提示
    ElMessage({
      message: errorMessage,
      type: 'error',
      duration: 5000,
      showClose: true
    });
  } finally {
    loading.value = false;
  }
};

/**
 * 处理键盘事件
 * @param {Event} event - 键盘事件对象
 */
const handleKeyPress = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    handleSendMessage(inputMessage.value);
  }
};

/**
 * 滚动消息容器到底部
 */
const scrollToBottom = () => {
  if (messageContainerRef.value) {
    messageContainerRef.value.scrollTop = messageContainerRef.value.scrollHeight;
  }
};

// 组件挂载时初始化
onMounted(() => {
  if (messageContainerRef.value) {
    messageContainerRef.value.scrollTop = messageContainerRef.value.scrollHeight;
  }
});

</script>
<!-- template 一个组件只能有一个根元素 -->
<template>  
    <div class="chatsonic-view">
        <el-row justify="center" class="el-row" >
            <el-col :span="24" class="center" style="height: 100%;">
                <h1 class="text-center">讯飞星火 AI Chat</h1>
                <!-- chatsonic AI组件页面内容 -->
                    <div class="chat-container">
                        <!-- 聊天主题 -->
                        <div v-if="chatTopic" class="chat-topic">
                            <el-icon>
                                <ChatDotRound />
                            </el-icon>
                            <span>当前话题: {{ chatTopic }}</span>
                        </div>

                        <!-- 消息列表 -->
                        <div ref="messageContainerRef" class="message-container">
                            <template v-if="messages.length === 0">
                                <div class="welcome-message">
                                    <el-icon class="service-icon">
                                        <Service />
                                    </el-icon>
                                    <h2>欢迎使用讯飞星火AI助手</h2>
                                    <p>我是讯飞星火大模型SparkPro，可以帮您回答问题、编写代码、撰写文章等。</p>
                                    <p>请在下方输入你的问题，按Enter发送。</p>
                                </div>
                            </template>
                            <template v-else>
                                <div v-for="(message, index) in messages" :key="index"
                                    :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']">
                                    <div class="message-avatar">
                                        <el-icon :size="36">
                                            <!-- <component :is="message.role === 'user' ? User : message.role === 'assistant' ? Service : null" /> -->
                                            <component
                                                :is="message.role === 'user' ? 'User' : message.role === 'assistant' ? 'Service' : null" />
                                        </el-icon>
                                    </div>
                                    <div class="message-content">
                                        <div class="message-text">{{ message.content }}</div>
                                        <div class="message-time">{{ new Date().toLocaleTimeString() }}</div>

                                    </div>
                                </div>
                            </template>
                        </div>

                        <!-- 输入区域 -->
                        <div class="input-container">
                            <el-input v-model="inputMessage" type="textarea" :rows="3"
                                :placeholder="loading ? '正在思考中...' : '输入消息，按Enter发送，Shift+Enter换行'"
                                @keydown="handleKeyPress" :disabled="loading" resize="none">
                                <template #prefix>
                                    <el-icon>
                                        <ChatLineRound />
                                    </el-icon>
                                </template>
                            </el-input>
                            <el-button type="primary" @click="handleSendMessage(inputMessage)" :loading="loading"
                                :disabled="!inputMessage.trim() || loading">
                                <el-icon v-if="!loading">
                                    <Position />
                                </el-icon>
                                <el-icon v-else>
                                    <Loading />
                                </el-icon>
                                <span>{{ loading ? '思考中...' : '发送' }}</span>
                            </el-button>
                        </div>
                    </div>

            </el-col>
        </el-row>
    </div>
</template>

<style lang="scss" scoped>

  @import '../assets/style/xunfei.scss';

</style>